package org.htzb.news.web;

import org.htzb.news.biz.UserBiz;
import org.htzb.news.biz.impl.UserBizImpl;
import org.htzb.news.dao.UserDao;
import org.htzb.news.dao.impl.UserDaoImpl;
import org.htzb.news.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    UserDao userDao = new UserDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String opr=req.getParameter("opr");
        if(opr==null||opr.length()==0){
            opr="login";
        }
        if(opr.equals("login")){
            //登录
            String username = req.getParameter("uname");//获取用户名
            String password = req.getParameter("upwd");//获取密码
            try {
                User user = userDao.findUser(username, password);
                if(user!=null){
                    //登录成功
                    req.getSession().setAttribute("admin", user);
                    resp.sendRedirect(req.getContextPath()+"/NewsServlet?opr=admin");
                    //登录成功跳转到新闻管理系统后台admin.jsp页面
                }else{
                    //登录失败
                    resp.sendRedirect(req.getContextPath()+"/NewsServlet");
                    //登录成功跳转到新闻管理系统首页index.jsp页面
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }else if(opr.equals("logout")){
            //退出
            req.getSession().removeAttribute("admin");
            req.getSession().invalidate();//session失效
            resp.sendRedirect((req.getContextPath()+"/NewsServlet"));
        }
    }
}
